package cm.example.shoppingplatformspringboot.service;


import cm.example.shoppingplatformspringboot.entity.User;
import cm.example.shoppingplatformspringboot.mapper.UserMapper;
import jakarta.annotation.Resource;
import org.jetbrains.annotations.NotNull;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Objects;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {
    String AVATAR_PATH = "https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png";
    @Resource
    private UserMapper userMapper;
    @Resource
    private RedisTemplate<String, String> redisTemplate;

    //根据手机号获取用户信息
    public User loginByPhone(String telphone, String last_login_ip) {
        // 根据手机号获取用户信息
        User user = userMapper.getUserByTelphone(telphone);
        // 未找到用户
        if (user == null) {
            return null;
        }

        // 更新登录信息
        userMapper.updateUserLoginInfo(user.getAccount(), last_login_ip);
        return userMapper.getUserByAccount(user.getAccount());
    }

    //登录
    public User login(String account, String password, String last_login_ip) {
        // 根据账号获取用户信息
        User user = userMapper.getUserByAccount(account);
        if (user == null) {
            return null;//没有该用户
        }

        //将密码转为md5加密字段
        String encryptedPassword = DigestUtils.md5DigestAsHex(password.getBytes());
        // 验证密码
        if (!user.getPassword().equals(encryptedPassword)) {
            return null;
        }

        // 更新登录信息
        userMapper.updateUserLoginInfo(user.getAccount(), last_login_ip);
        return userMapper.getUserByAccount(user.getAccount());
    }

    //注册方法
    public int registerUser(@NotNull User user) {
        // 1. 检查账号是否已存在
        User existingUser = userMapper.getUserByAccount(user.getAccount());
        if (existingUser != null) {
            return 0; // 账号已存在
        }
        int exitPhone = getUserByTelphone(user.getTelphone());
        if (exitPhone == 1) {
            return 2; // 手机号已注册
        }
        int exitEmail = getUserByEmail(user.getEmail());
        if (exitEmail == 1) {
            return 3; // 邮箱已绑定
        }

        // 2. 密码加密（MD5）
        String encryptedPassword = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        user.setPassword(encryptedPassword);
        user.setAvatar(AVATAR_PATH);
        // 3. 保存到数据库
        return userMapper.insertUser(user);
    }

    // 新增：更新用户信息
    public int updateUserInfo(@NotNull User user) {
        // 确保用户存在
        User existingUser = userMapper.getUserById(user.getId());
        if (existingUser == null) {
            return 0;
        }
        // 密码为空则不更新密码
        if (Objects.equals(user.getPassword(), "")) {
            user.setPassword(existingUser.getPassword());
        } else {
            // 密码加密（MD5）
            String encryptedPassword = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
            user.setPassword(encryptedPassword);
        }

        // 更新用户信息
        return userMapper.updateUser(user);
    }

    // 新增：获取用户信息
    public User getUserInfo(Integer userId) {
        return userMapper.getUserById(userId);
    }

    // 生成并发送验证码
    public String sendCode(String phone) {
        // 生成4位随机验证码
        String code = String.format("%04d", new Random().nextInt(10000));

        // 存储验证码到Redis（有效期2分钟）
        redisTemplate.opsForValue().set("login_code:" + phone, code, 2, TimeUnit.MINUTES);

        // 模拟发送验证码
        System.out.println("发送验证码到 " + phone + ": " + code);
        return code;
    }

    // 验证验证码
    public boolean verifyCode(String phone, String code) {
        String storedCode = redisTemplate.opsForValue().get("login_code:" + phone);
        if (storedCode == null || !storedCode.equals(code)) {
            return false;
        }
        // 验证成功后删除验证码
        redisTemplate.delete("login_code:" + phone);
        return true;
    }

    // 根据手机号获取用户(1:存在，0:不存在)
    public int getUserByTelphone(String phone) {
        return userMapper.countByTelphone(phone);
    }

    // 根据邮箱获取用户(1:存在，0:不存在)
    public int getUserByEmail(String email) {
        return userMapper.countByEmail(email);
    }
}
